<template>
  <div class="dashboard">
    <el-row :gutter="20">
      <el-col :span="6" v-for="room in rooms" :key="room.id">
        <el-card class="room-card" @click.stop="showRoomDevices(room.name)">
          <template #header>
            <div class="room-header">
              <span>{{ room.name }}</span>
              <el-tag size="small" type="success" v-if="room.devices.filter(d => d.status).length">
                {{ room.devices.filter(d => d.status).length }} 个设备运行中
              </el-tag>
            </div>
          </template>
          <div class="device-list">
            <div v-for="device in room.devices" :key="device.id" class="device-item">
              <div class="device-button" :class="{ 'device-on': device.status }" @click.stop="toggleDevice(device.id)">
                <div class="device-info">
                  <span class="device-name">{{ device.name }}</span>
                  <span class="device-status">{{ device.status ? '开启' : '关闭' }}</span>
                </div>
                <div class="device-controls">
                  <el-switch
                    v-model="device.status"
                    @change="() => toggleDevice(device.id)"
                    :active-color="'#13ce66'"
                    :inactive-color="'#ff4949'"
                    :active-value="true"
                    :inactive-value="false"
                  />
                  <el-button 
                    type="danger" 
                    circle
                    size="small"
                    @click.stop="removeDeviceConfirm(device)"
                    class="delete-btn">
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 房间设备详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="selectedRoom ? selectedRoom + ' - 设备控制' : ''"
      width="70%"
      :show-close="true"
      :close-on-click-modal="true"
      destroy-on-close>
      <div v-if="selectedRoom" class="room-devices">
        <div class="room-header mb-4">
          <h3>{{ selectedRoom }} 设备管理</h3>
          <el-button type="primary" @click="showAddDeviceDialog">
            <el-icon><Plus /></el-icon> 添加设备
          </el-button>
        </div>
        <el-row :gutter="20">
          <el-col :span="8" v-for="device in selectedRoomDevices" :key="device.id">
            <el-card class="device-card">
              <div class="device-header">
                <div class="device-title">
                  <span class="device-name">{{ device.name }}</span>
                  <el-tag size="small" :type="device.status ? 'success' : 'info'">
                    {{ device.status ? '开启' : '关闭' }}
                  </el-tag>
                </div>
                <div class="device-actions">
                  <el-switch
                    v-model="device.status"
                    @change="() => toggleDevice(device.id)"
                    :active-value="true"
                    :inactive-value="false"
                    :active-color="'#13ce66'"
                    :inactive-color="'#ff4949'"
                  />
                  <el-button 
                    type="danger" 
                    size="small" 
                    icon="Delete"
                    circle
                    @click="removeDeviceConfirm(device)">
                  </el-button>
                </div>
              </div>
              
              <!-- 灯光控制 -->
              <div v-if="device.type === 'light'" class="control-panel" :class="{ 'panel-disabled': !device.status }">
                <div class="control-wrapper" :class="{ 'disabled': !device.status }">
                  <span>亮度调节</span>
                  <el-slider
                    v-model="device.brightness"
                    :step="1"
                    :min="1"
                    :max="100"
                    :show-input="true"
                    :disabled="!device.status"
                    @change="(val) => updateDeviceProperty(device.id, 'brightness', val)">
                  </el-slider>
                </div>
              </div>

              <!-- 空调控制 -->
              <div v-if="device.type === 'ac'" class="control-panel" :class="{ 'panel-disabled': !device.status }">
                <div class="control-wrapper" :class="{ 'disabled': !device.status }">
                  <div class="control-item">
                    <span>温度设置</span>
                    <el-input-number
                      v-model="device.temperature"
                      :min="16"
                      :max="30"
                      :step="0.5"
                      size="small"
                      :disabled="!device.status"
                      @change="(val) => updateDeviceProperty(device.id, 'temperature', val)">
                    </el-input-number>
                  </div>
                  <div class="control-item">
                    <span>模式选择</span>
                    <el-select
                      v-model="device.mode"
                      size="small"
                      :disabled="!device.status"
                      @change="(val) => updateDeviceProperty(device.id, 'mode', val)">
                      <el-option label="制冷" value="cool"></el-option>
                      <el-option label="制热" value="heat"></el-option>
                      <el-option label="除湿" value="dry"></el-option>
                      <el-option label="送风" value="fan"></el-option>
                      <el-option label="自动" value="auto"></el-option>
                    </el-select>
                  </div>
                  <div class="control-item">
                    <span>风速调节</span>
                    <el-select
                      v-model="device.fanSpeed"
                      size="small"
                      :disabled="!device.status"
                      @change="(val) => updateDeviceProperty(device.id, 'fanSpeed', val)">
                      <el-option label="自动" value="auto"></el-option>
                      <el-option label="低速" value="low"></el-option>
                      <el-option label="中速" value="medium"></el-option>
                      <el-option label="高速" value="high"></el-option>
                    </el-select>
                  </div>
                </div>
              </div>

              <!-- 窗帘控制 -->
              <div v-if="device.type === 'curtain'" class="control-panel" :class="{ 'panel-disabled': !device.status }">
                <div class="control-wrapper" :class="{ 'disabled': !device.status }">
                  <span>开合度调节</span>
                  <el-slider
                    v-model="device.openness"
                    :step="1"
                    :min="0"
                    :max="100"
                    :show-input="true"
                    :disabled="!device.status"
                    @change="(val) => updateDeviceProperty(device.id, 'openness', val)">
                  </el-slider>
                </div>
              </div>

              <!-- 冰箱控制 -->
              <div v-if="device.type === 'fridge'" class="control-panel" :class="{ 'panel-disabled': !device.status }">
                <div class="control-wrapper" :class="{ 'disabled': !device.status }">
                  <div class="control-item">
                    <span>冷藏室温度</span>
                    <el-input-number
                      v-model="device.temperature"
                      :min="2"
                      :max="8"
                      :step="1"
                      size="small"
                      :disabled="!device.status"
                      @change="(val) => updateDeviceProperty(device.id, 'temperature', val)">
                    </el-input-number>
                  </div>
                  <div class="control-item">
                    <span>冷冻室温度</span>
                    <el-input-number
                      v-model="device.freezerTemp"
                      :min="-24"
                      :max="-16"
                      :step="1"
                      size="small"
                      :disabled="!device.status"
                      @change="(val) => updateDeviceProperty(device.id, 'freezerTemp', val)">
                    </el-input-number>
                  </div>
                  <div class="control-item">
                    <span>模式选择</span>
                    <el-select
                      v-model="device.mode"
                      size="small"
                      :disabled="!device.status"
                      @change="(val) => updateDeviceProperty(device.id, 'mode', val)">
                      <el-option label="正常" value="normal"></el-option>
                      <el-option label="假日" value="holiday"></el-option>
                      <el-option label="速冷" value="quick"></el-option>
                      <el-option label="节能" value="eco"></el-option>
                    </el-select>
                  </div>
                </div>
              </div>

              <!-- 热水器控制 -->
              <div v-if="device.type === 'waterHeater'" class="control-panel" :class="{ 'panel-disabled': !device.status }">
                <div class="control-wrapper" :class="{ 'disabled': !device.status }">
                  <div class="control-item">
                    <span>温度设置</span>
                    <el-input-number
                      v-model="device.temperature"
                      :min="35"
                      :max="75"
                      :step="1"
                      size="small"
                      :disabled="!device.status"
                      @change="(val) => updateDeviceProperty(device.id, 'temperature', val)">
                    </el-input-number>
                  </div>
                  <div class="control-item">
                    <span>模式选择</span>
                    <el-select
                      v-model="device.mode"
                      size="small"
                      :disabled="!device.status"
                      @change="(val) => updateDeviceProperty(device.id, 'mode', val)">
                      <el-option label="标准" value="normal"></el-option>
                      <el-option label="节能" value="eco"></el-option>
                      <el-option label="快速" value="quick"></el-option>
                      <el-option label="定时" value="timer"></el-option>
                    </el-select>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </el-dialog>

    <!-- 添加设备对话框 -->
    <el-dialog
      v-model="addDeviceDialogVisible"
      title="添加设备"
      width="40%"
      :close-on-click-modal="false">
      <el-form :model="newDevice" label-width="80px">
        <el-form-item label="设备名称">
          <el-input v-model="newDevice.name" placeholder="请输入设备名称"></el-input>
        </el-form-item>
        <el-form-item label="设备类型">
          <el-select v-model="newDevice.type" placeholder="请选择设备类型" @change="handleDeviceTypeChange">
            <el-option
              v-for="type in deviceTypes"
              :key="type.id"
              :label="type.name"
              :value="type.id">
            </el-option>
          </el-select>
        </el-form-item>
        
        <!-- 根据设备类型显示不同的初始配置选项 -->
        <template v-if="newDevice.type === 'light'">
          <el-form-item label="初始亮度">
            <el-slider v-model="newDevice.brightness" :min="1" :max="100"></el-slider>
          </el-form-item>
        </template>
        
        <template v-if="newDevice.type === 'ac'">
          <el-form-item label="初始温度">
            <el-input-number v-model="newDevice.temperature" :min="16" :max="30" :step="0.5"></el-input-number>
          </el-form-item>
          <el-form-item label="初始模式">
            <el-select v-model="newDevice.mode">
              <el-option label="制冷" value="cool"></el-option>
              <el-option label="制热" value="heat"></el-option>
              <el-option label="除湿" value="dry"></el-option>
              <el-option label="送风" value="fan"></el-option>
              <el-option label="自动" value="auto"></el-option>
            </el-select>
          </el-form-item>
        </template>
        
        <template v-if="newDevice.type === 'curtain'">
          <el-form-item label="初始开度">
            <el-slider v-model="newDevice.openness" :min="0" :max="100"></el-slider>
          </el-form-item>
        </template>
        
        <template v-if="newDevice.type === 'waterHeater'">
          <el-form-item label="初始温度">
            <el-input-number v-model="newDevice.temperature" :min="35" :max="75"></el-input-number>
          </el-form-item>
          <el-form-item label="初始模式">
            <el-select v-model="newDevice.mode">
              <el-option label="标准" value="normal"></el-option>
              <el-option label="节能" value="eco"></el-option>
              <el-option label="快速" value="quick"></el-option>
              <el-option label="定时" value="timer"></el-option>
            </el-select>
          </el-form-item>
        </template>
        
        <template v-if="newDevice.type === 'fridge'">
          <el-form-item label="冷藏温度">
            <el-input-number v-model="newDevice.temperature" :min="2" :max="8"></el-input-number>
          </el-form-item>
          <el-form-item label="冷冻温度">
            <el-input-number v-model="newDevice.freezerTemp" :min="-24" :max="-16"></el-input-number>
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDeviceDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAddDevice">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <el-row :gutter="20" class="mt-4">
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>能源消耗</span>
            </div>
          </template>
          <div ref="energyChart" style="height: 300px"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>设备状态概览</span>
            </div>
          </template>
          <div ref="deviceChart" style="height: 300px"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, onMounted, computed, onBeforeUnmount, watch, nextTick } from 'vue'
import { useStore } from 'vuex'
import * as echarts from 'echarts'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'

export default {
  name: 'Dashboard',
  components: {
    Plus,
    Delete
  },
  setup() {
    const store = useStore()
    const dialogVisible = ref(false)
    const addDeviceDialogVisible = ref(false)
    const selectedRoom = ref('')
    const energyChart = ref(null)
    const deviceChart = ref(null)
    const energyChartInstance = ref(null)
    const deviceChartInstance = ref(null)

    // 新设备表单数据
    const newDevice = ref({
      name: '',
      type: '',
      status: false,
      brightness: 50,
      temperature: 24,
      mode: 'normal',
      fanSpeed: 'auto',
      openness: 50,
      freezerTemp: -18
    })

    const rooms = computed(() => store.state.rooms)
    const deviceTypes = computed(() => store.state.deviceTypes)
    
    const selectedRoomDevices = computed(() => {
      const room = rooms.value.find(r => r.name === selectedRoom.value)
      return room ? room.devices : []
    })

    const getDevicesInRoom = (roomName) => {
      const room = rooms.value.find(r => r.name === roomName)
      return room ? room.devices : []
    }

    const getActiveDevicesCount = (roomName) => {
      const room = rooms.value.find(r => r.name === roomName)
      return room ? room.devices.filter(device => device.status).length : 0
    }

    const toggleDevice = (deviceId) => {
      store.dispatch('toggleDevice', deviceId)
    }

    const showRoomDevices = (roomName) => {
      console.log('显示房间设备:', roomName)
      selectedRoom.value = roomName
      nextTick(() => {
        dialogVisible.value = true
        console.log('对话框状态:', dialogVisible.value)
      })
    }

    const testDialog = () => {
      console.log('测试对话框')
      selectedRoom.value = '测试房间'
      dialogVisible.value = true
      console.log('对话框状态:', dialogVisible.value)
    }

    const initCharts = () => {
      if (energyChart.value) {
        energyChartInstance.value = echarts.init(energyChart.value)
        energyChartInstance.value.setOption({
          title: { text: '24小时能源消耗' },
          tooltip: { trigger: 'axis' },
          xAxis: {
            type: 'category',
            data: ['00:00', '03:00', '06:00', '09:00', '12:00', '15:00', '18:00', '21:00']
          },
          yAxis: { type: 'value' },
          series: [{
            data: [5, 3, 2, 4, 6, 5, 7, 4],
            type: 'line',
            smooth: true
          }]
        })
      }

      if (deviceChart.value) {
        deviceChartInstance.value = echarts.init(deviceChart.value)
        updateDeviceChart()
      }
    }

    const updateDeviceChart = () => {
      if (!deviceChartInstance.value) return

      const deviceTypes = store.state.deviceTypes
      const deviceCounts = deviceTypes.map(type => {
        const count = store.getters.devicesByType(type.id).length
        return { value: count, name: type.name }
      })

      deviceChartInstance.value.setOption({
        title: { text: '' },
        tooltip: { trigger: 'item' },
        legend: { orient: 'vertical', left: 'left' },
        series: [{
          type: 'pie',
          radius: '50%',
          data: deviceCounts,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      })
    }

    const updateDeviceProperty = (deviceId, property, value) => {
      store.dispatch('updateDeviceProperty', {
        deviceId,
        property,
        value
      })
    }

    // 重置新设备表单
    const resetNewDevice = () => {
      newDevice.value = {
        name: '',
        type: '',
        status: false,
        brightness: 50,
        temperature: 24,
        mode: 'normal',
        fanSpeed: 'auto',
        openness: 50,
        freezerTemp: -18
      }
    }

    // 显示添加设备对话框
    const showAddDeviceDialog = () => {
      resetNewDevice()
      addDeviceDialogVisible.value = true
    }

    // 处理设备类型变化
    const handleDeviceTypeChange = (type) => {
      // 根据设备类型设置默认值
      switch (type) {
        case 'light':
          newDevice.value.brightness = 50
          break
        case 'ac':
          newDevice.value.temperature = 24
          newDevice.value.mode = 'cool'
          newDevice.value.fanSpeed = 'auto'
          break
        case 'curtain':
          newDevice.value.openness = 50
          break
        case 'waterHeater':
          newDevice.value.temperature = 45
          newDevice.value.mode = 'normal'
          break
        case 'fridge':
          newDevice.value.temperature = 4
          newDevice.value.freezerTemp = -18
          newDevice.value.mode = 'normal'
          break
      }
    }

    // 添加设备
    const handleAddDevice = () => {
      if (!newDevice.value.name || !newDevice.value.type) {
        ElMessage.warning('请填写设备名称和类型')
        return
      }

      store.dispatch('addDevice', {
        roomName: selectedRoom.value,
        device: { ...newDevice.value }
      })

      ElMessage.success('设备添加成功')
      addDeviceDialogVisible.value = false
    }

    // 删除设备确认
    const removeDeviceConfirm = (device) => {
      ElMessageBox.confirm(
        `确定要删除设备 "${device.name}" 吗？`,
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        store.dispatch('removeDevice', {
          roomName: selectedRoom.value,
          deviceId: device.id
        })
        ElMessage.success('设备已删除')
      }).catch(() => {})
    }

    // 监听对话框状态变化
    watch(dialogVisible, (newVal) => {
      console.log('对话框状态变化:', newVal)
      if (!newVal) {
        selectedRoom.value = ''
      }
    })

    // 监听 rooms 变化，自动刷新设备状态概览图表
    watch(() => store.state.rooms, () => {
      nextTick(() => {
        if (deviceChartInstance.value) {
          updateDeviceChart()
        }
      })
    }, { deep: true })

    onMounted(() => {
      nextTick(() => {
        initCharts()
        window.addEventListener('resize', () => {
          if (energyChartInstance.value) {
            energyChartInstance.value.resize()
          }
          if (deviceChartInstance.value) {
            deviceChartInstance.value.resize()
          }
        })
        // 初始渲染时也刷新一次设备图表
        updateDeviceChart()
      })
    })

    onBeforeUnmount(() => {
      if (energyChartInstance.value) {
        energyChartInstance.value.dispose()
      }
      if (deviceChartInstance.value) {
        deviceChartInstance.value.dispose()
      }
    })

    return {
      rooms,
      dialogVisible,
      selectedRoom,
      selectedRoomDevices,
      getDevicesInRoom,
      getActiveDevicesCount,
      toggleDevice,
      showRoomDevices,
      energyChart,
      deviceChart,
      updateDeviceProperty,
      deviceTypes,
      addDeviceDialogVisible,
      newDevice,
      showAddDeviceDialog,
      handleDeviceTypeChange,
      handleAddDevice,
      removeDeviceConfirm
    }
  }
}
</script>

<style scoped>
.dashboard {
  padding: 20px;
}

.room-card {
  margin-bottom: 20px;
  cursor: pointer;
  transition: all 0.3s;
  user-select: none;
}

.room-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
}

.room-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  h3 {
    margin: 0;
    font-size: 20px;
    color: var(--el-text-color-primary);
  }
}

.device-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.device-item {
  width: 100%;
}

.device-button {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background-color: var(--el-fill-color-blank);
  border: 1px solid var(--el-border-color);
  border-radius: 8px;
  transition: all 0.3s ease;
  cursor: pointer;
}

.device-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.device-button.device-on {
  background-color: var(--el-color-primary-light-9);
  border-color: var(--el-color-primary-light-5);
}

.device-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.device-name {
  font-size: 16px;
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.device-status {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.device-controls {
  display: flex;
  align-items: center;
  gap: 12px;
}

.delete-btn {
  opacity: 0;
  transition: opacity 0.3s ease;
}

.device-button:hover .delete-btn {
  opacity: 1;
}

.mt-4 {
  margin-top: 20px;
}

.room-devices {
  padding: 20px;
}

.device-card {
  margin-bottom: 20px;
}

.device-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.device-title {
  display: flex;
  align-items: center;
  gap: 10px;
}

.device-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.mb-4 {
  margin-bottom: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.el-form-item:last-child {
  margin-bottom: 0;
}

.control-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.control-item:last-child {
  margin-bottom: 0;
}

.el-slider {
  margin-top: 8px;
}

.el-select,
.el-input-number {
  width: 120px;
}

.card-header {
  font-weight: bold;
}

.el-dialog {
  .control-panel {
    background-color: var(--el-bg-color-overlay);
    border-radius: 4px;
    padding: 15px;
  }

  .device-card {
    height: 100%;
  }

  .el-slider {
    width: 100%;
  }
}
</style> 